class AdminStorage {
  constructor() {
    this.storage = window.localStorage;
    this.sessionStorage = window.sessionStorage;

  }
  setLocal(res, key = 'STORAGE_USER_KEY', isSaveOldData = false) {
    //第三个参数是true的话,会增加数据而不是重新设置,res必须是数组
    if (isSaveOldData) {
      if (this.getLocal(key)) {
        let oldData = this.getLocal(key);
        return this.storage.setItem(key, JSON.stringify(oldData.concat(res)))
      }
    }
    return this.storage.setItem(key, JSON.stringify(res))
  }
  setSession(res, key = 'STORAGE_USER_KEY', isSaveOldData = false) {
    if (isSaveOldData) {
      if (this.getSession(key)) {
        let oldData = this.getSession(key);
        return this.sessionStorage.setItem(key, JSON.stringify(oldData.concat(res)))
      }
    }
    return this.sessionStorage.setItem(key, JSON.stringify(res))
  }
  // 获取
  getLocal(key = 'STORAGE_USER_KEY') {
    return JSON.parse(this.storage.getItem(key))
  }
  // 获取
  getSession(key = 'STORAGE_USER_KEY') {
    return JSON.parse(this.sessionStorage.getItem(key))
  }
  // 清空缓存
  clearLocal(key = 'STORAGE_USER_KEY', isAll = false) {
   
    // removeItem()：从 localStorage 中删除指定的键值对
    // clear()：清空 localStorage 中所有键值对
    if (isAll) {
      this.sessionStorage.clear()
      this.storage.clear()
    }
     this.storage.removeItem(key)
  }
}
export const adminStorage = new AdminStorage();
export const observer = () => {
  // 监听localStorage存储变化
  let changeStorage = (res, key = 'STORAGE_USER_KEY') => {
    if(typeof key!=='string')return
    return window.localStorage.setItem(key, JSON.stringify(res))
  }
  adminStorage.setLocal = (res, key = 'STORAGE_USER_KEY', isSaveOldData = false) => {
    let setEvent = new Event('changeStorage')
    setEvent.res = res
    setEvent.key = key
    setEvent.isSaveOldData = isSaveOldData
    window.dispatchEvent(setEvent)
    changeStorage.apply(this,arguments)
  }
}

export default { adminStorage, observer }
